package com.demo.reggie.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.reggie.common.R;
import com.demo.reggie.entity.Category;
import com.demo.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category 前端传来的分类参数
     * @return 消息实体
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("保存成功");
    }

    /**
     * 分类分页查询
     * @param jsonObject 查询传参
     * @return 分页数据
     */
    @PostMapping("/page")
    public R<Page<Category>> page(@RequestBody JSONObject jsonObject) {
        // 获取分页参数
        Integer page = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Category category = jsonObject.toJavaObject(Category.class);

        // 创建分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);

        // 创建查询构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        queryWrapper.like(category.getName() != null, Category::getName, category.getName());
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());

        // 添加排序条件
        queryWrapper.orderByAsc(Category::getSort);

        // 调用 categoryService 进行数据查询
        categoryService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 根据id删除分类
     * @param id 分类id
     * @return 消息实体
     */
    @DeleteMapping
    public R<String> deleteById(Long id) {
        categoryService.removeById(id);
        return R.success("删除成功");
    }

    /**
     * 根据id修改分类
     * @param category 分类数据
     * @return 消息实体
     */
    @PutMapping
    public R<String> updateById(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }
}
